﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;

public class ResultCompent : BaseCompent {

//	public static Dictionary<string,UIPanel> panelMap = new Dictionary<string,UIPanel> ();
	public static AudioSource compareAudioSource;
	private static UIAtlas atlas;
	private static UIPanel restartPanel;
	private static UIPanel totalPanel;
	private static List<User> users = new List<User> ();	//特殊拍用户
	private static Dictionary<UISprite,Vector3> originPosition = new Dictionary<UISprite,Vector3> ();


	public static void ResetResultPokers(User user){
		UIPanel resultPanel = user.resultContainer;
		resultPanel.gameObject.SetActive (true);
		users.Clear ();

		for (int i = 1; i < 4; i++) {
			GetGameObjectByName<UISprite> (resultPanel.gameObject, "Line"+i.ToString()).gameObject.SetActive(false);	
			GetGameObjectByName<UILabel> (resultPanel.gameObject, "Label"+i.ToString()).gameObject.SetActive(false);	
		}

		for (int i =1; i < 14; i++) {
			UISprite sprite = GetGameObjectByName<UISprite> (resultPanel.gameObject, "Poker" + i.ToString ());
			sprite.gameObject.SetActive(true);	
			sprite.spriteName = "Card";
			sprite.transform.eulerAngles = new Vector3(0,0,0);
		}

		//清理打枪结果
		UISprite gun = GetGameObjectByName<UISprite>(resultPanel.gameObject,"Gun");
		UISprite hole = GetGameObjectByName<UISprite>(resultPanel.gameObject,"Hole");
		UISprite homeRun = GetGameObjectByName<UISprite>(resultPanel.gameObject,"Home Run");
		UISprite teshu = GetGameObjectByName<UISprite>(resultPanel.gameObject,"teshu");
		if (gun != null) {
			NGUITools.Destroy (gun.gameObject);
		}
		while (hole != null) {
			NGUITools.Destroy (hole.gameObject);
			hole = GetGameObjectByName<UISprite>(resultPanel.gameObject,"Hole");
		}
			
		if (homeRun != null) {
			NGUITools.Destroy (homeRun.gameObject);
		}
		if (teshu != null) {
			NGUITools.Destroy (teshu.gameObject);
		}
		//恢复位置
		foreach(var s in originPosition.Keys){
			s.transform.position = originPosition [s];
		}
		originPosition.Clear ();
	}

	public static void ResetMyResultPokers(){
		ResetResultPokers(Main.room.players [0]);

		//清理结果面板里每个User
		for (int i = 1; i < 7; i++) {
			UISprite user = GetGameObjectByName<UISprite>(totalPanel.gameObject,"User"+i);
			if (user != null) {
				Debug.Log ("清理User");
				NGUITools.Destroy (user.gameObject);
//				NGUITools.Destroy (user.transform);
//				Destroy (user);
			}
				
		}
	}

	public static void DestroyPanel(){

		totalPanel.gameObject.SetActive (false);
		restartPanel.gameObject.SetActive (false);

		for (int j = 0; j < Main.room.players.Count; j++) {
			User user = Main.room.players [j];
			UIPanel resultPanel = user.resultContainer;

			resultPanel.gameObject.SetActive (false);
		}
	}
		
	/// <summary>
	/// 动画控制器	 MAIN
	/// </summary>
	/// <returns>The animation.</returns>
	public static IEnumerator StartAnimation(){

		yield return new WaitForSeconds (0.1f);

		API.GetStatistics ();

		//计算特殊牌
		Dictionary<string,JSONObject> resultJSONMap = GetresultJSONMap ();
		foreach (var result in resultJSONMap.Values) {
			//如果是特殊牌型
			if (bool.Parse (result ["submit_res_scores"]["is_special"].ToString ())) {
				users.Add (GetUser (result ["player_id"].str));
			}
		}

		//比牌动画
		yield return new WaitForSeconds (ResultCompent.ComScore ());

		//特殊拍报道
		yield return new WaitForSeconds (ResultCompent.ReportAnimation());

		//打枪
		yield return new WaitForSeconds (ResultCompent.ShowAllWinAnimation());

		//结果面板
		ResultCompent.End();
	}


	//报到动画控制
	public static float ReportAnimation(){
		if (users.Count == 0)
			return 0f;

		for(int i=0;i<users.Count;i++){
			//扇形动画
			//1.移动到第一张牌的位置,并隐藏
			User user = users[i];
			List<TweenPosition> pokersPosition = new List<TweenPosition> ();
			UISprite pokerCenter = GetGameObjectByName<UISprite> (user.resultContainer.gameObject, "Poker2");
			Vector3 startPosition = pokerCenter.transform.position;
			for(int j=1;j<14;j++){
				UISprite poker = GetGameObjectByName<UISprite> (user.resultContainer.gameObject, "Poker"+j);
				//记录初始位置
				originPosition.Add (poker, poker.transform.position);
				poker.alpha = 0;
				pokersPosition.Add(TweenPosition.Begin (poker.gameObject, 0.3f, startPosition));
			}


			//2.计算每张牌的位置，并开始动画
			float offsetX = pokerCenter.width * 3 / 7;
			float offsetY = pokerCenter.height / 7;
			float rotationRange = 100;

			Dictionary<string,JSONObject> resultJSONMap = GetresultJSONMap ();
			string[] cards = GetCardList (resultJSONMap[user.id]);
			for(int j=0;j<13;j++){
				float x = (j - 7) * offsetX + (offsetX/2);
				int idx = Mathf.Abs(j - 6);
				float y = (pokerCenter.height *2 * Mathf.Sqrt (49 - (idx * idx))) / 7 - (pokerCenter.height *2);
				float rotation =  (rotationRange / 2) - (j*(rotationRange / 13));
				UISprite poker = GetGameObjectByName<UISprite> (user.resultContainer.gameObject, "Poker"+(j+1));
				poker.spriteName = Utils.getLocalPorker (cards[j]);

				poker.StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>{
					TweenAlpha.Begin (poker.gameObject, 0.3f, 1);
					TweenPosition.Begin (poker.gameObject, 0.3f, new Vector3 (x, y, -10));
					poker.transform.eulerAngles = new Vector3(0,0,rotation);
				}, j * 0.01f));

			}

			//3.添加牌型提示
//			string type = Utils.getSpecial(cards).type;
			JSONObject json = resultJSONMap [user.id];
			string type = json["submit_res_scores"]["type"].str;
			UISprite sprite = NGUITools.AddSprite(user.resultContainer.gameObject,
				ResultCompent.atlas,
				Utils.GetLocalTeShuSprite(type));
			sprite.name = "teshu";
			sprite.width = (int)offsetX * 10;
			sprite.height = (int)sprite.width / 4;
			TweenPosition.Begin (sprite.gameObject, 0.3f, new Vector3 (pokerCenter.transform.position.x, 
				pokerCenter.transform.position.y - (offsetY * 4),
				-10));
			EffectUtil.PlayWithSpecial (Utils.GetLocalTeShuSprite (type), user.sex);
		}

		return 1f * users.Count;
	}

	//打枪动画
	public static float ShowAllWinAnimation(){
		List<User> users = new List<User> ();
		bool flag = false;	//全垒打标志

		//重新标志打枪与被打枪人
		foreach(var _result in Main.room.data["results_list"].list){
			foreach (var result in _result["one_vs_one_list"].list) {
				int multiple = int.Parse (result ["multiple"].ToString ());
				if (multiple == 1)
					continue;

				if (multiple == 4) {
					flag = true;
				}
				int winOrFail = int.Parse (result ["top"].ToString ());
				User user = GetUser (result ["player_id"].str);
				//如果是打枪的人,排入第一个
				if(!users.Contains(user)){
					if (winOrFail < 0) {
						users.Insert (0, user);
					} else{
						users.Add (user);
					}	
				}
			}
		}

		//计算打枪或者全垒打
//		Dictionary<string,JSONObject> resultJSONMap = GetresultJSONMap ();


		//如果没有人有倍数，不打枪
		if (users.Count <= 1) {
			return 0;
		}
			
		//判断是打枪还是全垒打
		if (flag) {
			QuanLeiDaAnimation (users);
			return 1.5f;
		} else {
			DaQiangAnimation (users);
			return users.Count * 1.5f;
		}
	}

	//全垒打动画
	private static void QuanLeiDaAnimation(List<User> users){
		User user = users [1];
		EffectUtil.QuanLeiDa (user.sex);
		UISprite sprite = NGUITools.AddSprite(user.resultContainer.gameObject,ResultCompent.atlas,"Home Run");
		sprite.name = "Home Run";
		UISprite pokerCenter = GetGameObjectByName<UISprite> (user.resultContainer.gameObject, "Poker11");
		sprite.width = pokerCenter.width * 4;
		sprite.height = pokerCenter.width * 2;
		sprite.alpha = 0;
		TweenScale.Begin (sprite.gameObject, 0.000001f, new Vector3 (0, 0, 0));

		TweenAlpha.Begin (sprite.gameObject, 0.3f, 1);
		TweenScale.Begin (sprite.gameObject, 1f, new Vector3 (1, 1, 1));
		TweenPosition.Begin (sprite.gameObject, 1f, new Vector3 (-(user.resultContainer.transform.position.x * 360),
			-(user.resultContainer.transform.position.y * 360), 0));

		//其他人子弹
//		for (int i = 0; i < users.Count; i++) {
//			User u = users [i];
//			if(u.id == user.id){
//				continue;
//			}
//			UISprite _pokerCenter = GetGameObjectByName<UISprite> (u.resultContainer.gameObject, "Poker6");
//			for(int j=0;j<8;j++){	
//				//与最中间的牌对其
//				UISprite _sprite = NGUITools.AddSprite(users[i].resultContainer.gameObject,ResultCompent.atlas,"Hole");
//				TweenScale.Begin(_sprite.gameObject,0.000001f,new Vector3(0,0,0));
//				_sprite.name = "Hole_sprite";
//				_sprite.alpha = 0;
//				_sprite.width = (int)(_pokerCenter.width / 1.5);
//				_sprite.height = (int)(_pokerCenter.width / 1.5);
//
//				float randomX = new System.Random().Next(-(_pokerCenter.width),_pokerCenter.width);
//				float randomY = new System.Random ((int)DateTime.Now.ToFileTimeUtc())
//					.Next((int)-(_pokerCenter.width * 1.5f),(int)(_pokerCenter.width * 0.5f ));
//
//				float delay = ((float)j * 0.125f) + 1f;
//
//				_sprite.gameObject.SetActive(true);
//				_sprite.StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>{
//					TweenScale.Begin(_sprite.gameObject,0.125f,new Vector3(1,1,1));
//					TweenAlpha.Begin(_sprite.gameObject,0.125f,1);
//					TweenPosition.Begin(_sprite.gameObject,0.0001f,new Vector3 (
//						(_pokerCenter.transform.position.x + (randomX)),
//						(_pokerCenter.transform.position.y+ (randomY)),
//						-10));
//				}, delay));	
//			}
//
//		}
	}

	//打枪动画
	private static void DaQiangAnimation(List<User> users){
		UISprite gunSprite = null;
		for (int i = 0; i < users.Count; i++) {
			User user = users [i];
			UISprite pokerCenter = GetGameObjectByName<UISprite> (user.resultContainer.gameObject, "Poker6");

			if (i == 0) {
				UISprite sprite = NGUITools.AddSprite(user.resultContainer.gameObject,ResultCompent.atlas,"Gun");
				sprite.alpha = 0;
				TweenScale.Begin(sprite.gameObject,0.01f,new Vector3(0,0,0));
				sprite.name = "Gun";
				sprite.width = pokerCenter.width * 3;
				sprite.height = pokerCenter.width * 2;
				sprite.transform.position = new Vector3 (pokerCenter.transform.position.x,pokerCenter.transform.position.y,-10);

				user.resultContainer.StartCoroutine (DelayToInvoke.DelayToInvokeDo (() => {
					sprite.gameObject.SetActive (true);
					gunSprite = sprite;
					EffectUtil.DaQiang (user.sex);
					TweenScale.Begin (sprite.gameObject, 0.1f, new Vector3 (1, 1, 1));
					TweenAlpha.Begin (sprite.gameObject, 0.01f, 1);
				}, 0.1f));	
			} else {

				user.resultContainer.StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>{
					EffectUtil.DaQiangYinXiao ();

					///计算方法
					/// 1.y/x = tanå
					/// 2.r = Mathf.Sqrt(x*x + y*y)
					/// 3.rotation = Mathf.Atan(y/x) / Mathf.PI * 180
					//角度
					float parentX = gunSprite.transform.parent.position.x;
					float parentY = gunSprite.transform.parent.position.y;
					float targetX = user.resultContainer.transform.position.x;
					float targetY = user.resultContainer.transform.position.y;
					float baseAdjust = 0;
					if(targetX-parentX <= 0 && targetY - parentY > 0){
						baseAdjust = 90;
					}else if(targetX - parentX < 0 && targetY - parentY <= 0){
						baseAdjust = -180;
					}else if(targetX - parentX >= 0 && targetY - parentY < 0){
						baseAdjust = -90;
					}
					float r = (targetX - parentX) / (targetY-parentY);
					float baseRoration = (float)(Math.Atan(r) / Math.PI * 180) + baseAdjust;// + (targetY > parentY ? 90f:targetY == parentY ? 0 : -90f);

					//枪动画
					for(int j = 1;j<16;j++){
						float dur = (float)j * 0.0625f;
						float roration = ((j%2==0?10:0) + baseRoration);
//						Debug.Log(roration);
						user.resultContainer.StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>{
							TweenRotation.Begin(gunSprite.gameObject,0.0625f,
								Quaternion.Euler(new Vector3(0,0,roration)));	
						}, (dur-0.0625f)));		
					}
				}, (1 * i)));	

				for(int j=0;j<8;j++){	
					//与最中间的牌对其
					UISprite sprite = NGUITools.AddSprite(user.resultContainer.gameObject,ResultCompent.atlas,"Hole");
					TweenScale.Begin(sprite.gameObject,0.000001f,new Vector3(0,0,0));
					sprite.name = "Hole";
					sprite.alpha = 0;
					sprite.width = (int)(pokerCenter.width / 1.5);
					sprite.height = (int)(pokerCenter.width / 1.5);

					float randomX = new System.Random().Next(-(pokerCenter.width),pokerCenter.width);
					float randomY = new System.Random ((int)DateTime.Now.ToFileTimeUtc())
						.Next((int)-(pokerCenter.width * 1.5f),(int)(pokerCenter.width * 0.5f ));

					float delay = ((float)j * 0.125f) + (1f * i);

					sprite.gameObject.SetActive(true);
					sprite.StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>{
						TweenScale.Begin(sprite.gameObject,0.125f,new Vector3(1,1,1));
						TweenAlpha.Begin(sprite.gameObject,0.125f,1);
						TweenPosition.Begin(sprite.gameObject,0.0001f,new Vector3 (
							(pokerCenter.transform.position.x + (randomX)),
							(pokerCenter.transform.position.y+ (randomY)),
							-10));
					}, delay));	
				}
			}
		}
		Debug.Log ("打枪动画");
	}

	private static User GetUser(string id){
		foreach (var p in Main.room.players) {
			if (p.id == id)
				return p;
		}
		return null;
	}

	private static string[] GetCardList(JSONObject json){
		List<string> cards = new List<string> ();
		if (json ["submit_res_cards"]["all"] != null) {
			foreach (var c in json["submit_res_cards"]["all"].list) {
				cards.Add (c.str);
			}
		} else {
			foreach (var s in json["submit_res_cards"]["top"].list)
				cards.Add (s.str);
			foreach (var s in json["submit_res_cards"]["mid"].list)
				cards.Add (s.str);
			foreach (var s in json["submit_res_cards"]["btm"].list)
				cards.Add (s.str);	
		}

		return cards.ToArray ();
	}

	private static void GunAnimation(UISprite sprite,float duration){
		float subDur = duration / 5;
		for(int i= 0;i<5;i++){
			sprite.StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>{
				TweenRotation.Begin(sprite.gameObject,subDur / 2,new Quaternion (0, 0, i % 2 == 0? 1 : -1, 1));
			}, subDur * i));
		}
	}

	private static Dictionary<string,JSONObject> GetresultJSONMap(){
		Dictionary<string,JSONObject> resultJSONMap = new Dictionary<string,JSONObject> ();
		if (Main.room.data["results_list"] == null || Main.room.data["results_list"].list.Count == 0)
			return new Dictionary<string,JSONObject>();
		foreach(var result in Main.room.data["results_list"].list){
			foreach (var r in result ["one_vs_one_list"].list) {
				if (!resultJSONMap.ContainsKey (r ["player_id"].str)) {
					resultJSONMap.Add (r ["player_id"].str, r);
				}
			}
		}
		return resultJSONMap;
	}

	private static List<User> GetResulList(int line){
		List<User> players = Main.room.players;
		List<User> vailUser = new List<User> ();
		foreach (var p in players) {
			JSONObject json = GetresultJSONMap () [p.id];
			if (!bool.Parse(json["is_special"].ToString())) {
				vailUser.Add (p);
			}
		}

		Dictionary<string,JSONObject> resultJSONMap = GetresultJSONMap ();

		//排序
		string key = line == 0 ? "top" : line == 1 ? "mid": line == 2? "btm" : "";
		if (key == "") {
			Debug.Log ("比牌排序出错"); 
			key="top";
		}
		vailUser.Sort(delegate(User p1, User p2)
			{
				if(p1.id == p2.id){
					return 0;
				}
				JSONObject p1JSON = resultJSONMap[p1.id];
				JSONObject p2JSON = resultJSONMap[p2.id];
				int p1Weight = int.Parse(p1JSON["submit_res_scores"][key]["handle_weight"].ToString());
				int p2Weight = int.Parse(p2JSON["submit_res_scores"][key]["handle_weight"].ToString());
				if(!p1Weight.Equals(p2Weight)){
					return p1Weight.CompareTo(p2Weight);	
				}else{
					//将牌重新排序
					int p1Line = int.Parse(resultJSONMap[p1.id]["submit_res_scores"] [key]["weights_value"].ToString());
					int p2Line = int.Parse(resultJSONMap[p2.id]["submit_res_scores"] [key]["weights_value"].ToString());
					return p1Line.CompareTo(p2Line);
//					List<JSONObject> p1Line = resultJSONMap[p1.id]["submit_res_cards"] [key].list;
//					List<JSONObject> p2Line = resultJSONMap[p2.id]["submit_res_cards"] [key].list;
//					p1Line.Sort(new CardJSONComparer());
//					p2Line.Sort(new CardJSONComparer());
//					for(int i=0;i<p1Line.Count;i++){
//						if(Utils.comparePoker(p1Line[i].str,p2Line[i].str) == 0){
//							continue;
//						}else{
//							return Utils.comparePoker(p1Line[i].str,p2Line[i].str);
//						}
//					}
//					return 0;
				}
			});
		return vailUser;
	}


	public static void InitRestartPanel(UIPanel totalPanel,UIPanel restartPanel,UIAtlas atlas,AudioSource compareAudioSource){
		if(ResultCompent.restartPanel == null)
			ResultCompent.restartPanel = restartPanel;
		if(ResultCompent.atlas == null)
			ResultCompent.atlas = atlas;
		if (ResultCompent.totalPanel == null)
			ResultCompent.totalPanel = totalPanel;
		if (ResultCompent.compareAudioSource == null)
			ResultCompent.compareAudioSource = compareAudioSource;

//		Share Button
		UIButton button = GetGameObjectByName<UIButton>(restartPanel.gameObject,"Share Button");
		UIEventListener.Get (button.gameObject).Clear ();
		UIEventListener.Get (button.gameObject).onClick += Share;
	}



	//开始比分
	 public static float ComScore(){
		EffectUtil.KaishiBiPai (Main.user.sex);
		Dictionary<string,JSONObject> resultMap = GetresultJSONMap ();

		for (int i = 0; i < 3; i++) {
			
//			foreach (var player in Main.room.players) {
			foreach (var player in GetResulList(i)) {
				if (bool.Parse (resultMap[player.id] ["submit_res_scores"] ["is_special"].ToString ())) {
					continue;
				}

				for (int j = 0; j < 13; j++) {
					UISprite sprite = GetGameObjectByName<UISprite> (player.resultContainer.gameObject, "Poker" + (j + 1));
					sprite.alpha = 0;
					sprite.transform.localRotation = new Quaternion (0, 90, 0, 1);
				}
				Animation (i, player,resultMap[player.id]);
			}
		} 

		return 3 * (Main.room.players.Count - users.Count) + 1;
	}

	private static void Animation(int i,User player,JSONObject result){

		List<User> players = GetResulList(i);
		List<User> vailUser = new List<User> ();
		foreach (var p in players) {
			JSONObject json = GetresultJSONMap () [p.id];
			string type = json["submit_res_scores"]["type"].str;
			if (type == "") {
				vailUser.Add (p);
			}
		}

		float dur = (i*0.9f) * (Main.room.players.Count - users.Count) + (vailUser.IndexOf (player)*0.9f)  + 1.5f;
		player.resultContainer.gameObject.SetActive (true);


		player.resultContainer.StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
			{
				//显示牌型
				for(int j =0;j< (i == 0?3:5);j++){

					UISprite sprite = player.resultContainer.transform.GetChild (j + (i==1?3:i==2?8:0)).gameObject.GetComponent<UISprite>();	
					if (i == 0) {
						sprite.spriteName = Utils.getLocalPorker (result["submit_res_cards"] ["top"].list [j].str);		
					} else if (i == 1) {
						sprite.spriteName = Utils.getLocalPorker (result["submit_res_cards"] ["mid"].list [j].str);
					}else {
						sprite.spriteName = Utils.getLocalPorker (result["submit_res_cards"] ["btm"].list [j].str);		
					}

					TweenAlpha.Begin(sprite.gameObject,0.3f,1);
					TweenRotation.Begin(sprite.gameObject,0.3f,new Quaternion (0, 0, 0, 1));
				}

				UILabel label = null;
				UISprite line = null;
				if(i == 0){
					line = player.resultContainer.gameObject.transform.GetChild (13).gameObject.GetComponent<UISprite>();
					//判断冲三
					if(CartType.three.GetHashCode() == int.Parse(result["submit_res_scores"]["top"]["handle_weight"].ToString())){
						Utils.ShowResultPaixing(CartType.top_three.GetHashCode().ToString(),line);
						EffectUtil.PlayWithPaixing(CartType.top_three.GetHashCode().ToString(),player.sex,compareAudioSource);
					}else{
						Utils.ShowResultPaixing(result["submit_res_scores"]["top"]["handle_weight"].ToString(),line);
						EffectUtil.PlayWithPaixing(result["submit_res_scores"]["top"]["handle_weight"].ToString(),player.sex,compareAudioSource);	
					}
					//显示分数 16,17,18
//					label = parent.gameObject.transform.GetChild (16).gameObject.GetComponent<UILabel>();	
//					label.text = resultMap [player.id]["top"].ToString();
				}else if(i == 1){
					line = player.resultContainer.gameObject.transform.GetChild (14).gameObject.GetComponent<UISprite>();
					//判断是否中盾葫芦
					if(CartType.full_house.GetHashCode() == int.Parse(result["submit_res_scores"]["top"]["handle_weight"].ToString())){
						Utils.ShowResultPaixing(CartType.mid_full_house.GetHashCode().ToString(),line);
						EffectUtil.PlayWithPaixing(CartType.mid_full_house.GetHashCode().ToString(),player.sex,compareAudioSource);
					}else{
						Utils.ShowResultPaixing(result["submit_res_scores"]["mid"]["handle_weight"].ToString(),line);
						EffectUtil.PlayWithPaixing(result["submit_res_scores"]["mid"]["handle_weight"].ToString(),player.sex,compareAudioSource);	
					}

//					label = parent.gameObject.transform.GetChild (17).gameObject.GetComponent<UILabel>();	
//					label.text = resultMap [player.id]["mid"].ToString();
				}else if(i == 2){
					line = player.resultContainer.gameObject.transform.GetChild (15).gameObject.GetComponent<UISprite>();
					Utils.ShowResultPaixing(result["submit_res_scores"]["btm"]["handle_weight"].ToString(),line);
					EffectUtil.PlayWithPaixing(result["submit_res_scores"]["btm"]["handle_weight"].ToString(),player.sex,compareAudioSource);
//					label = parent.gameObject.transform.GetChild (18).gameObject.GetComponent<UILabel>();	
//					label.text = resultMap [player.id]["btm"].ToString();
				}

//				if(player.id != Main.user.id && label != null){
//					int scroe = int.Parse(label.text);
//					label.text = (-scroe).ToString();
//				}

				TweenAlpha.Begin(line.gameObject,0.3f,1);

				if(i == 2){
					int point = int.Parse(result["top"].ToString()) + 
						int.Parse(result["mid"].ToString())+
						int.Parse(result["btm"].ToString());

					label = player.resultContainer.gameObject.transform.GetChild (17).gameObject.GetComponent<UILabel>();	
					label.text = (-point).ToString();
					label.gameObject.SetActive (true);
					label.alpha = 0;
//					TweenAlpha.Begin(label.gameObject,0.3f,1);	
				}
			},dur));
	}


	public static void End(){

		if (Main.room.curRound > 0) {
			TotalPanel ();
		} else {
			RestartPanel ();
		}
	}

	//重启面板是否可以继续游戏
	public static void RestartContinueHandler(){
		UIButton restartButton = GetGameObjectByName<UIButton> (restartPanel.gameObject, "Continue Button");
		//是否可以继续游戏
		if (Main.room.maxRound-Main.room.curRound > 0) {
			restartButton.GetComponent<UISprite> ().spriteName = "Icon Continue1";
			restartButton.isEnabled = true;
		} else {
			//我是房主
			if (Main.room.owner != null && Main.room.owner.id == Main.user.id) {
				restartButton.GetComponent<UISprite> ().spriteName = "Icon Recharge1";
			} else {
				restartButton.isEnabled = false;
			}
		}
	}

	//小局结束时
	public static void TotalPanel(){
		totalPanel.gameObject.SetActive (true);

		//背景
		UISprite background = GetGameObjectByName<UISprite>(totalPanel.gameObject,"Background");
		background.gameObject.SetActive (true);

		//结果整理
		Dictionary<string,JSONObject> resultMap = new Dictionary<string,JSONObject>();
		foreach (var result in Main.room.data["results_list"].list) {
			resultMap.Add (result ["player_id"].str, result);
		}

		Dictionary<string,JSONObject> resultPokerMap = GetresultJSONMap ();

		List<UISprite> resultPanels = new List<UISprite> ();

		for (int i = 0; i < (Main.room.players.Count <= 4 ? 4 : Main.room.players.Count); i++) {
			GameObject uesr = (GameObject)Resources.Load ("Home/User Item");
			UISprite sprite = NGUITools.AddChild (background.gameObject, uesr).GetComponent<UISprite>();
			sprite.name = "User" + (i + 1);	
			//获取用户名
			UILabel name = GetGameObjectByName<UILabel> (sprite.gameObject, "Name Label");
			UILabel each = GetGameObjectByName<UILabel> (sprite.gameObject, "Each Label");
			UILabel total = GetGameObjectByName<UILabel> (sprite.gameObject, "Total Label");

			if (i < Main.room.players.Count) {
				name.text = Main.room.players [i].username;
				each.text = resultMap [Main.room.players [i].id] ["total"].ToString ();
				total.text = stastisticsMap.ContainsKey(Main.room.players[i].id) ? stastisticsMap [Main.room.players[i].id] : "未收到结果";

				JSONObject result = resultPokerMap [Main.room.players [i].id];
				//展示牌
				for (int j = 0; j < 13; j++) {
					UISprite poker = GetGameObjectByName<UISprite> (sprite.gameObject, "Poker" + (j + 1));	
					string spriteName = "";
					if (result ["submit_res_cards"]["all"] != null) {
						spriteName = Utils.getLocalPorker (result ["submit_res_cards"] ["all"].list [j].str);
					} else {
						if (j < 3) {
							spriteName = Utils.getLocalPorker (result ["submit_res_cards"] ["top"].list [j].str);
						} else if (j < 8) {
							spriteName = Utils.getLocalPorker (result ["submit_res_cards"] ["mid"].list [j - 3].str);
						} else {
							spriteName = Utils.getLocalPorker (result ["submit_res_cards"] ["btm"].list [j - 8].str);
						}	
					}
					poker.spriteName = spriteName;
				}
			} else {
				sprite.spriteName = "GameEndNobody";
				name.gameObject.SetActive (false);
				each.gameObject.SetActive (false);
				total.gameObject.SetActive (false);
				for (int j = 0; j < 13; j++) {
					UISprite poker = GetGameObjectByName<UISprite> (sprite.gameObject, "Poker" + (j + 1));
					poker.gameObject.SetActive (false);
				}
			}

			resultPanels.Add (sprite);
		}

		//重新排版
		for(int i = 0;i<resultPanels.Count;i++){
			float width = resultPanels [i].width;
			float x = (i * width) + (width / 2) + (10 * i);
			float totalWidth = (resultPanels.Count * (width + 10));
			TweenPosition.Begin (resultPanels [i].gameObject, 0.3f, new Vector3 ((x - (totalWidth / 2)), 0, 0));
		}
	
		//隐藏显示按钮
		UISprite tigger = GetGameObjectByName<UISprite> (totalPanel.gameObject, "Tigger Button");
		tigger.spriteName = "Total Hidden 1";
		UIEventListener.Get (tigger.gameObject).Clear ();
		UIEventListener.Get (tigger.gameObject).onClick += TotalTigger;

		//重启按钮
		UISprite button = GetGameObjectByName<UISprite> (totalPanel.gameObject, "Sure");
		UIEventListener.Get (button.gameObject).Clear ();
		UIEventListener.Get (button.gameObject).onClick = RestartAction;
		//分享按钮
		UISprite share = GetGameObjectByName<UISprite> (totalPanel.gameObject, "Share");
		UIEventListener.Get (share.gameObject).Clear ();
		UIEventListener.Get (share.gameObject).onClick += Share;
	}

	//结果面板隐藏显示
	private static void TotalTigger(GameObject gameObject){
		UISprite background = GetGameObjectByName<UISprite>(totalPanel.gameObject,"Background");
		background.gameObject.SetActive (!background.gameObject.activeInHierarchy);
		if (background.gameObject.activeInHierarchy) {
			gameObject.GetComponent<UISprite> ().spriteName = "Total Hidden 1";
		} else {
			gameObject.GetComponent<UISprite> ().spriteName = "Total Show";
		}
	}

	//结束游戏时
	public static void RestartPanel(){
		restartPanel.gameObject.SetActive (true);
		UIButton restartButton = GetGameObjectByName<UIButton> (restartPanel.gameObject, "Continue Button");
		UIButton leaveButton = GetGameObjectByName<UIButton> (restartPanel.gameObject, "Leave Room Button");


		UIEventListener.Get (restartButton.gameObject).Clear ();
		UIEventListener.Get (leaveButton.gameObject).Clear ();
		UIEventListener.Get (restartButton.gameObject).onClick += RestartAction;
		UIEventListener.Get (leaveButton.gameObject).onClick += LeaveAction;

		//结果整理
		Dictionary<string,JSONObject> resultMap = new Dictionary<string,JSONObject>();
		foreach (var result in Main.room.data["results_list"].list) {
			resultMap.Add (result ["player_id"].str, result);
		}

		//展示信息
		for(int i = 0;i<Main.room.players.Count;i++){
			GameObject icon = GetGameObjectByName<UIWidget> (restartPanel.gameObject, "Result Icon" + (i+1)).gameObject;
			icon.SetActive (true);

			UITexture avatar = GetGameObjectByName<UITexture> (icon, "Texture");
			UILabel name = GetGameObjectByName<UILabel> (icon, "Name");
			UILabel id = GetGameObjectByName<UILabel> (icon, "ID");
			UILabel point = GetGameObjectByName<UILabel> (icon, "Point");

			User player = Main.room.players [i];
			name.text = player.username;
			id.text = player.id;
			point.text = stastisticsMap [player.id];
			Main.ImageDownload.SetAsyncImage (player.headImgUrl,avatar);

			//定位位置
			RePosition(icon.GetComponent<UIWidget>(),i);
		}

	}

	private static  Dictionary<string,string> stastisticsMap = new Dictionary<string,string> ();
	public static void HandlerStastistics(string obj){
		stastisticsMap.Clear ();
		JSONObject json = new JSONObject (obj);
		for (int i = 0; i < json ["players"].list.Count; i++) {
			stastisticsMap.Add (json ["players"][i] ["id"].str, json ["players"] [i]["total"].ToString ());
		}
	}

	private static void RePosition(UIWidget obj,int idx){
		//需要展示的个数
		int maxEle = Main.room.players.Count;
		//单个宽度
		float width = obj.CalculateBounds().max.x - obj.CalculateBounds().min.x + 100;
		float leftX = - maxEle * width / 2;
		float x = leftX + (idx * width) + (width / 2);

		TweenPosition.Begin (obj.gameObject, 0, new Vector3 (x, obj.transform.position.y, -10));
	}

	private static void Share(GameObject gameObject){

		string imagePath = "";
		string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff") + ".png";
//		Application.CaptureScreenshot(fileName);  
		Application.CaptureScreenshot(fileName);

		#if UNITY_ANDROID || UNITY_IOS
		imagePath = Application.persistentDataPath + "/"+fileName;
		#endif

		#if UNITY_ANDROID
		AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
		AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
		jo.Call("shareResult",imagePath);
		#endif

		#if UNITY_IOS
		SDKTool.ShareResult (imagePath);
		#endif


		#if UNITY_EDITOR
		Debug.Log("点击分享");
		#endif

	}

	private static void RestartAction(GameObject obj){
		EffectUtil.DianJi();
		if (Main.room.curRound == 0) {
			API.RechargeGame ();
		}
		API.RestartGame ();	


	}

	private static void LeaveAction(GameObject obj){
		EffectUtil.DianJi();
		API.LeaveRoom ();
		SceneManager.LoadScene ("Home");
	}
		
}
